<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background-color: rgb(251, 251, 251);
        }

        img {
            width: 300px;
            height: 300px;
            position: absolute;
            left: 0;
            top: 50%;

        }
    </style>
</head>

<body>
    <img src="./小熊.gif" alt="">
</body>
<script>
    var w;
    var img = document.querySelector('img');
    var imgLeft;//左边位置
    var imgWidth;// 图片宽度
    var len = 5;//每次移动的距离
    window.onload = function () {
        w = window.innerWidth
        imgLeft = img.offsetLeft;
        imgWidth = img.width;
        // console.log(w, img, imgLeft, imgWidth);
        move()

    }
    function move() {
        if (imgLeft < 0 || imgLeft + imgWidth > w - 5) {
            len = -len
        }
        img.style.left = imgLeft + len + 'px'
        //移动位置后需要重新修改左边的位置
        imgLeft = img.offsetLeft
        //重复不断调用函数
        t = setTimeout(move, 5)
    }

</script>

</html>